import { defineComponent, computed, unref } from 'vue';
import { createFromIconfontCN } from '@ant-design/icons-vue';
import { isString } from '@/utils';

let scriptUrls = ['https://at.alicdn.com/t/font_3361017_fuwe36wltjt.js'];

let MyIconFont = createFromIconfontCN({
  scriptUrl: scriptUrls,
});

export default defineComponent({
  name: 'IconFont',
  props: {
    name: {
      type: String,
      default: '',
    },
    prefix: {
      type: String,
      default: 'icon-',
    },
    color: {
      type: String,
      default: 'unset',
    },
    size: {
      type: [Number, String],
      default: 14,
    },
    scriptUrl: {
      // 阿里图库字体图标路径
      type: String,
      default: '',
    },
  },
  setup(props, { attrs }) {
    props.scriptUrl;

    // 如果外部传进来字体图标路径，则覆盖默认的
    if (props.scriptUrl) {
      scriptUrls = [
        ...new Set([
          ...scriptUrls,
          ...(props.scriptUrl instanceof Array ? [...props.scriptUrl] : props.scriptUrl),
        ]),
      ];
      MyIconFont = createFromIconfontCN({
        scriptUrl: scriptUrls,
      });
    }
    const wrapStyleRef = computed(() => {
      const { color, size } = props;

      const fs = isString(size) ? parseFloat(size) : size;

      return {
        color,
        fontSize: `${fs}px`,
      };
    });
    return () => {
      const { name, prefix } = props;

      return name ? (
        <MyIconFont
          type={name.startsWith(prefix) ? name : `${prefix}${name}`}
          {...attrs}
          style={unref(wrapStyleRef)}
        />
      ) : null;
    };
  },
});
